<?php

namespace App\Http\Controllers\Pay;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use App\Exceptions\RuleValidationException;
use App\Models\User;
use Illuminate\Validation\ValidationException; // 引入 ValidationException

class YpayController extends Controller
{
    public function gateway(Request $request)
    {
        $validator = $request->validate([
            'payway' => 'required|string',  // 必须是字符串
            'amount' => 'required|numeric', // 必须是数字
            'userId' => 'required|integer'  // 必须是整数
        ]);
    
       
        $payway = $request->input('payway');
        $amount = $request->input('amount');
        $userId = $request->input('userId');
       
        
        //创建订单
        $orderdata=[
            'order_sn' => date('YmdHis') . str_pad($userId, 4, '0', STR_PAD_LEFT) . str_pad(rand(1000, 9999), 4, '0', STR_PAD_LEFT),
            'user_id'=>$userId,
            'amount'=>$amount, //订单金额
            'payway'=>$payway,
            'status'=>0, //订单状态
            'created_at' => now(), // 添加创建时间
            'updated_at' => now(), // 添加更新时间
        ];
        $order = Order::create($orderdata);

        try {
            
            //组装支付参数
            $parameter = [
                'pid' =>  admin_setting('ypay_id'),
                'type' => $payway,
                'out_trade_no' => $order->order_sn, // 使用创建订单的order_sn
                'return_url' => url( '/pay/epay/return_url'),
                'notify_url' => url('/pay/epay/notify_url'),
                'name'   => "用户:".$userId.",充值余额" . $order->amount . "元", // 修复字符串拼接语法错误
                'money'  => $order->amount, // 使用创建订单的amount
                'sign_type' =>'MD5'
            ];
            ksort($parameter); //重新排序$data数组
            reset($parameter); //内部指针指向数组中的第一个元素
            $sign = '';
            foreach ($parameter as $key => $val) {
                if ($key == "sign" || $key == "sign_type" || $val == "") continue;
                if ($key != 'sign') {
                    if ($sign != '') {
                        $sign .= "&";
                    }
                    $sign .= "$key=$val"; //拼接为url参数形式
                }
            }

            $sign = md5($sign . admin_setting('ypay_key'));//密码追加进入开始MD5签名
            $parameter['sign'] = strtolower($sign); // 强制转小写
            //待请求参数数组
            $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".admin_setting('ypay_url')."submit.php' method='get'>";

            foreach($parameter as $key => $val) {
                $sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
            }

            //submit按钮控件请不要含有name属性
            $sHtml = $sHtml."<input type='submit' value=''></form>";
            $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
            return $sHtml;
        } catch (RuleValidationException $exception) {
            return $this->err($exception->getMessage());
        }
    }

    public function notifyUrl(Request $request)
    {
        $data = $request->all();
        $order = Order::where('order_sn', $data['out_trade_no'])->first();
        $user=User::find($order->user_id)->first();
        if (!$order) {
            return 'fail';
        }
        ksort($data);
        reset($data);
        $sign = '';
        foreach ($data as $key => $val) {
            if ($key == "sign" || $key == "sign_type" || $val == "") continue;
            if ($key != 'sign') {
                if ($sign != '') {
                    $sign .= "&";
                }
                $sign .= "$key=$val";
            }
        }
        // 修改验签逻辑，移除strtolower并调整参数
        if (!$data['trade_no'] || md5($sign . admin_setting('ypay_key')) != $data['sign']) { 
            return 'fail';  
        } else {
            // 增加支付状态校验，确保只有成功状态才充值
            if (!isset($data['trade_status']) || $data['trade_status'] !== 'TRADE_SUCCESS') {
                return 'fail';
            }
            // 充值余额逻辑
            $user->increment('balance', $order->amount);
            // 新增：更新订单状态为已完成（假设状态码1表示已完成）
            $order->update(['status' => 1,'transaction_id'=>$data['trade_no'],'completed_at'=>now(),'callback_data'=>json_encode($data)]);
            return 'success';
        }
    }

    public function returnUrl(Request $request)
    {
        
        $oid = $request->get('order_id');
        // 有些易支付太垃了，异步通知还没到就跳转了，导致订单显示待支付，其实已经支付了，所以这里休眠2秒
        sleep(2);
        return redirect()->to('/user')->with('status', '充值成功');
    }
}
